package com.wch.clientdemo.module.base.util;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.json.JSONArray;
import org.json.JSONObject;

import com.google.gson.JsonArray;

/**
 * 
 * @author WanChengHe 
 * @Date 20181119
 * json工具类
 *
 */
public class JsonUtil {

	/**
	 * JSON对象转map
	 * @param json
	 * @return
	 */
	public static Map<String, Object> toMap(JSONObject json){
		Map<String, Object> map = new HashMap<String,Object>();
		Iterator<?> keys = json.keys();
		while (keys.hasNext()) {
			String key = (String) keys.next();
			try {
				Object object = json.get(key);
				if(object instanceof JsonArray){
					
				}else if(object instanceof JSONObject){
					object = toMap((JSONObject) object);
				}
				
				map.put(key, object);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return map;	
	}
	
	/**
	 * json数组转化为list
	 * @param json
	 * @return
	 */
	public static List<Object> toList(JSONArray json){
		List<Object> result = new ArrayList<Object>();
		int size = json.length();
		for(int i=0;i<size;i++){
			try {
				Object object = json.get(i);
				if(object instanceof JSONObject){
					object = toMap((JSONObject) object);
				}else if(object instanceof JSONArray){
					object = toList((JSONArray) object);
				}
				
				result.add(object);
			} catch (Exception e) {
				// TODO: handle exception
				e.printStackTrace();
			}
		}
		return result;		
	}
	
}
